package service.local.beans;

import java.util.List;

import javax.ejb.*;

import model.Role;
import model.User;
import repository.UserRepository;
import repository.exceptions.RepositoryException;
import service.ServiceException;
import service.local.UserService;
import util.PasswordProvider;

@Stateless(name = "UserService", mappedName = "UserService")
@DependsOn({ "UserRepository" })
public class UserServiceBean implements UserService {

	@EJB
	UserRepository repo;

	@Override
	public User insertUser(User user){
		try {
			String hash=PasswordProvider.generateHashedPassword(user.getPassword(), "");
			user.setPassword(hash);
			return repo.save(user);
		} catch (final RepositoryException ex) {
		
		}
		return null;
	}

	@Override
	public void deleteUser(User user){
		try {
			if (repo.getById(user.getId()) != null) {
				repo.delete(user);
			} else {
				
			}
		} catch (final RepositoryException ex) {
			
		}

	}

	@Override
	public User getUser(Long id){
		try {
			return repo.getById(id);
		} catch (final RepositoryException ex) {
	
		}
		return null;
	}

	@Override
	public User updateUser(User user){
		try {
			if (repo.getById(user.getId()) != null) {
				return repo.merge(user);
			} else {
				
			}
		} catch (final RepositoryException ex) {
			
		}
		return null;
	}

	@Override
	public List<User> getAllUsers(){
		try {
			return repo.getAll();
		} catch (final RepositoryException ex) {
		
		}
		return null;
	}

	@Override
	public User getUserByUsername(String username){
		try {
			return repo.getUserByUsername(username);
		} catch (final RepositoryException ex) {
			
		}
		return null;
	}

	@Override
	public List<Role> getRolesForUser(Long id){
		try {
			return repo.getRolesForUser(id);
		} catch (final RepositoryException ex) {
		}
		return null;
	}

	@Override
	public boolean tryLogin(String username, String pass) {
		if(this.getUserByUsername(username)!=null){
			if(this.getUserByUsername(username).getPassword().equals(PasswordProvider.generateHashedPassword(pass, ""))){
				return true;
			}
		}
		return false;
	}

	@Override
	public List<User> getAllActiveUsers() {
		try {
			return repo.getAllActiveUsers();
		} catch (final RepositoryException ex) {
		
		}
		return null;
	}

}
